<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择单据状态" clearable>
          <el-option
            v-for="dict in dict.type.py_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调拨单号" prop="transferNumber">
        <el-input
          v-model="queryParams.transferNumber"
          placeholder="请输入调拨单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="调拨申请日期" prop="requestDate">
        <el-date-picker clearable
          v-model="queryParams.requestDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择调拨申请日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出库状态" prop="sourceStatus">
        <el-select v-model="queryParams.sourceStatus" placeholder="请选择出库状态" clearable>
          <el-option
            v-for="dict in dict.type.od_inventory_transfer"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['transfer:transfer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['transfer:transfer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['transfer:transfer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['transfer:transfer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed label="序号" align="center" prop="inventoryTransferId" />
      <el-table-column fixed label="调拨单号" align="center" prop="transferNumber" width="180px">
        <template slot-scope="scope">
          <router-link
            :to="{path:'/wms/transfer/transfer/query',query:{inventoryTransferId:scope.row.inventoryTransferId}}"
            tag="span"
            style="color: blue; cursor: pointer;"
          >
            {{ scope.row.transferNumber }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column fixed label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.py_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column fixed label="调拨类型" align="center" prop="transferType">
        <template slot-scope="scope">
          <el-span v-if="scope.row.transferType==1">货品调拨</el-span>
          <el-span v-if="scope.row.transferType==2">库存调拨</el-span>
          <el-span v-if="scope.row.transferType==3">满仓调离</el-span>
          <el-span v-if="scope.row.transferType==4">其他调拨</el-span>
        </template>
      </el-table-column>
      <el-table-column  label="调拨申请日期" align="center" prop="requestDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调出仓库" align="center" prop="dcku">
</el-table-column>
      <el-table-column label="调入仓库" align="center" prop="dlku">
      </el-table-column>
      <el-table-column label="出库状态" align="center" prop="sourceStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.od_inventory_transfer" :value="scope.row.sourceStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="入库状态" align="center" prop="destinationStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.od_inventory_transfer" :value="scope.row.destinationStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="调拨数量" align="center" prop="transferQuantity" />
      <el-table-column label="调拨金额" align="center" prop="transferAmount" />
      <el-table-column label="经办人" align="center" prop="operator" />
      <el-table-column label="备注" align="center" prop="notes" width="180px"/>
      <el-table-column label="制单人" align="center" prop="creator" />
      <el-table-column label="所在部门" align="center" prop="departmentId" />
      <el-table-column label="审核人" align="center" prop="reviewer" />
      <el-table-column label="审核时间" align="center" prop="reviewTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reviewTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="伪删除标识" align="center" prop="isDeleted" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
           v-if="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['transfer:transfer:audit']"
          >审核</el-button>
          <el-button
           v-if="scope.row.status!=4"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['transfer:transfer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['transfer:transfer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存调拨对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="调拨单号" prop="transferNumber" label-width="120px" >
          <el-input v-model="form.transferNumber" placeholder="请输入调拨单号" readonly/>
        </el-form-item>
        <el-form-item label="调拨类型" prop="transferType" label-width="120px" >
          <el-select v-model="form.transferType" placeholder="请选择调拨类型" :disabled="isEditing">
            <el-option
              v-for="dict in transferTypes"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调拨申请日期" prop="requestDate" label-width="120px">
          <el-date-picker clearable
            v-model="form.requestDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择调拨申请日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="调出仓库" prop="outboundWarehouseId"  label-width="120px">
          <el-select v-model="form.outboundWarehouseId" @change="DconWarehouseChange" placeholder="请选择调出仓库">
            <el-option
              v-for="ware in this.WareList "
              :key="ware.warehouseCode"
              :value="ware.warehouseId"
              :label="ware.warehouseName"

            />
          </el-select>
        </el-form-item>
        <el-form-item label="调入仓库" prop="inboundWarehouseId" label-width="120px">
          <el-select v-model="form.inboundWarehouseId"  @change="DlonWarehouseChange"  placeholder="请选择调入仓库">
            <el-option
              v-for="ware in this.WareList "
              :key="ware.warehouseCode"
              :value="ware.warehouseId"
              :label="ware.warehouseName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经办人" prop="operator" label-width="120px">
          <el-input v-model="form.operator" placeholder="请选择经办人" disabled label-width="100px">
            <template #append>
              <el-button @click="selUserall" icon="el-icon-search"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="" label-width="120px">
          <el-input v-model="form.notes" placeholder="请输入备注" />
        </el-form-item>

        <el-divider content-position="center">调拨明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOdTransferDetails">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOdTransferDetails">删除</el-button>
          </el-col>
        </el-row>
        <el-table ref="odTransferDetailsList" :data="odTransferDetailsList" :row-class-name="rowOdTransferDetailsIndex" @selection-change="handleOdTransferDetailsSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
         <!--  <el-table-column label="ID" prop="whInventoryList[0].inventoryQueryId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.whInventoryList[0].inventoryQueryId" placeholder="请输入产品编码" />
            </template>
          </el-table-column> -->
          <el-table-column label="序号" align="center"  type="index" :index="indexMethod" width="50"/>
          <el-table-column label="货品名称" prop="productName" width="150">
          <!--   <template slot-scope="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入产品名称" />
            </template> -->
          </el-table-column>
          <el-table-column label="货品编码" prop="productCode" width="150">
           <!--  <template slot-scope="scope">
              <el-input v-model="scope.row.productCode" placeholder="请输入产品编码" />
            </template> -->
          </el-table-column>
          <el-table-column label="货品型号" prop="specificationNumber" width="150">
           <!--  <template slot-scope="scope">
              <el-input v-model="scope.row.productModel" placeholder="请输入规格型号" />
            </template> -->
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="150">
            <!-- <template slot-scope="scope">
              <el-input v-model="scope.row.productUnit" placeholder="请输入单位" />
            </template> -->
            <template slot-scope="scope">
                      <dict-tag :options="dict.type.py_product_unit" :value="scope.row.unit"/>
            </template>
          </el-table-column>
          <el-table-column label="商品类型" prop="productType" width="150">
          </el-table-column>
          <el-table-column label="调出仓库当前库存" prop="outboundWarehouseId" width="150">
           <!--  <template slot-scope="scope">
              <el-input v-model="scope.row.whInventoryList[0].currentInventory" placeholder="请输入调出仓库当前库存" />
            </template> -->
          </el-table-column>
          <el-table-column label="调入仓库当前库存" prop="inboundWarehouseId" width="150">
           <!--  <template slot-scope="scope">
              <el-input v-model="scope.row.whInventoryList[0].currentInventory" placeholder="请输入调入仓库当前库存" />
            </template> -->

          </el-table-column>
          <el-table-column label="调拨数量" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.transferQuantity" type="number" min="0" step="1" @change="calculateSalesAmount(scope.row)"/>
            </template>
          </el-table-column>

          <el-table-column label="调入仓库库位" prop="dlLocationCode" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.dlLocationCode" placeholder="请选择"
                  @change="(value) => DlfetchwhLocationContact(value, scope.row.productCode, scope.row)">
                  <el-option v-for="item in dlwhLocation" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="调出仓库库位" prop="dcLocationCode" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.dcLocationCode" placeholder="请选择"
                  @change="(value) => DcfetchwhLocationContact(value, scope.row.productCode, scope.row)">
                  <el-option v-for="item in dcwhLocation" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
          <el-table-column label="入库单价" prop="inboundPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inboundPrice" placeholder="请输入入库单价" />
            </template>
          </el-table-column>
          <el-table-column label="调拨金额" prop="" width="150">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.transferAamount" placeholder="请输入调拨金额" /> -->
               {{Number(scope.row.transferQuantity*scope.row.inboundPrice)}}
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="notes" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.notes" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="伪删除标识" prop="isDeleted" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.isDeleted" placeholder="请输入伪删除标识" />
            </template>
          </el-table-column> -->
        </el-table>
        <div align="right">&nbsp;
          <span>合计：货品种类 {{ totalProductCategory }}，货品数量 {{ totalProductQuantity }}，总金额 {{ totalAmount }}</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--明细弹框-->
    <el-dialog :title="添加货品" :visible.sync="Goodsopen" width="1100px" append-to-body>
      <el-form :model="queryGoods" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="货品编号" prop="product_code">
          <el-input
            v-model="queryGoods.product_code"
            placeholder="请输入货品编号"
            clearable
            @keyup.enter.native=""
          />
        </el-form-item>
        <el-form-item label="货品名称" prop="productName">
          <el-input
            v-model="queryGoods.product_name"
            placeholder="请输入货品名称"
            clearable
            @keyup.enter.native=""
          />
        </el-form-item>
        <el-form-item label="货品单位" prop="productUnit">
          <el-select v-model="queryGoods.productUnit" placeholder="请选择货品单位" clearable>
            <el-option
              v-for="dict in dict.type.sys_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="selGoodsAll">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="goodsloading" :data="goodsListAll" @selection-change="goodsClick">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="型号" align="center" prop="productId"/>
        <el-table-column label="货品编号" align="center" prop="productCode"/>
        <el-table-column label="货品名称" align="center" prop="productName"/>
        <el-table-column label="货品类型" align="center" prop="productType"/>
        <el-table-column label="货品规格" align="center" prop="productModel"/>
        <el-table-column label="货品单位" align="center" prop="productUnit">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.py_product_unit" :value="scope.row.productUnit"/>
          </template>
        </el-table-column>
        <el-table-column label="出库参考价" align="center" prop="outboundPrice"/>
        <el-table-column label="当前库存" align="center" prop="whInventoryList[0].currentInventory"/>
        <!-- <el-table-column label="可用库存" align="center" prop="whInventoryList[0].currentInventory"/> -->
      </el-table>
      <pagination
        v-show="goodsTotal>0"
        :total="goodsTotal"
        :page.sync="queryGoods.pageNum"
        :limit.sync="queryGoods.pageSize"
        @pagination="selGoodsAll"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getGoodsClickRows">确 定</el-button>
        <el-button @click="getGoodsClickCount">取 消</el-button>
      </div>
    </el-dialog>
     <!--经办人弹框-->
     <el-dialog :title="选择经办人" :visible.sync="jhOpen" width="900px" append-to-body>
      <el-form :model="userQueryParams" ref="queryForm2" size="small" :inline="true"
               v-show="userShowSearch" label-width="92px">
        <el-form-item label="经办人名称" prop="userName" label-width="110px">
          <el-input
            v-model="userQueryParams.userName"
            placeholder="请输入经办人名称"
            clearable
            @keyup.enter.native="selUserall"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phonenumber">
          <el-input
            v-model="userQueryParams.phonenumber"
            placeholder="请输入电话号码"
            clearable
            @keyup.enter.native="selUserall"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="selUserall">搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery2">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="userLoading" :data="userList" @row-dblclick="userClick">
        <el-table-column label="经办人编码" align="center" prop="userId"/>
        <el-table-column label="经办人名称" align="center" prop="userName"/>
        <el-table-column label="部门" align="center" prop="dept.deptName"/>
        <el-table-column label="联系电话" align="center" prop="phonenumber"/>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_notice_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="userTotal>0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="getList"
      />
    </el-dialog>
    <el-dialog :visible.sync="auditOptionVisible" title="审计确认">
      <el-radio v-model="auditOption" label="4">通过</el-radio>
      <el-radio v-model="auditOption" label="1">驳回</el-radio>
      <span slot="footer" class="dialog-footer">
        <el-button @click="auditOptionVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAudit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listTransfer, getTransfer, delTransfer, addTransfer, updateTransfer, getCode, updateAllocate, selectAllBsWhLocation, selectWhInventoryByCode } from "@/api/transfer/transfer";
import { getUser, listUser } from "@/api/system/user";
import { listWarehouse } from "@/api/warehouse/warehouse";
import { selectquery,xgai } from "@/api/product/product";
export default {
  name: "Transfer",
  dicts: ['py_status', 'od_inventory_transfer', 'sys_notice_status', 'od_transfer_details', 'py_product_unit'],
  data() {
    return {
      // 库位
      dlwhLocation: [],
      dcwhLocation: [],
      //
      selectedGoods: [],
      // 显示新增货品弹框
      Goodsopen: false,
      // 出库货品列表
      goodsListAll: [],
      goodsInfo: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedOdTransferDetails: [],
      // 仓库表
      odWarehouseList: [],
      // 库存表
      WhInventoryList: [],
      WhInventoryList1: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存调拨表格数据
      transferList: [],

      transferList1: [],
      // 调拨明细表格数据
      odTransferDetailsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        transferNumber: null,
        requestDate: null,
        sourceStatus: null,
        destinationStatus: null
      },

      queryGoods: {
        pageNum: 1,
        pageSize: 5,
        warehouseName: null,
        productCode: null,
        productName: null,
        productType: null
      },
      // 经办人查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        phonenumber: null,
        status: null,
        deptId: null
      },
      // 进货负责人遮罩层
      userLoading: true,
      // 是否显示进货负责人弹出层
      jhOpen: false,
      // 仓库数据列表
      WareList: [],
      // 是否允许查询条
      userShowSearch: true,
      // 管理员总条数
      userTotal: 0,
      // 用户列表
      userList: [],
      auditOptionVisible: false,
      auditOption: null,
      // 表单参数
      form: {
        dllocationCode: null,
        dclocationCode: null,
        Editing: true,
        isEditing: true,
        status: null,
        transferNumber: null,
        transferType: null,
        requestDate: null,
        outboundWarehouseId: null,
        inboundWarehouseId: null,
        sourceStatus: null,
        destinationStatus: null,
        transferQuantity: null,
        transferAmount: null,
        operator: null,
        notes: null,
        creator: null,
        departmentId: null,
        createTime: null,
        reviewer: null,
        reviewTime: null,
        isDeleted: null,
        allocationOfGoods: null,
        odTransferDetails: {
          transferDetailId: null,
          transferNumber: null,
          productName: null,
          productCode: null,
          specificationNumber: null,
          unit: null,
          productType: null,
          outboundWarehouseId: null,
          inboundWarehouseId: null,
          transferQuantity: null,
          inboundPrice: null,
          transferAmount: null,
          notes: 'admin',
          isDeleted: null,
          odTransferDetailsList: []
        },
        whInventoryList: [],
        inventoryQueryId: null,
        productCode: null,
        warehouseCode: null,
        productUnit: null,
        currentInventory: null,
        locationCode: null,
        inventoryValue: null,
        pendingIn: null,
        pendingOut: null,
        availableInventoryValue: null,
        inventoryUpperLimit: null,
        inventoryLowerLimit: null
      },
      transferTypes: [
        { value: '1', label:'货品调拨' },
        { value: '2', label:'库存调拨' },
        { value: '3', label:'满仓调离' },
        { value: '4', label:'其他调拨' }
      ],
      number: undefined,
      codeId: undefined,
      totalProductCategory: 0, // 货品种类合计
      totalProductQuantity: 0, // 货品数量合计
      totalAmount: 0.00, // 总金额合计
      kuchun: [],
      isClick: true,
      // 表单校验
      rules: {
        transferType: [
          { required: true, message: "调拨类型不能为空", trigger: "change" }
        ],
        requestDate: [
          { required: true, message: "调拨申请日期不能为空", trigger: "blur" }
        ],
        outboundWarehouseId: [
          { required: true, message: "调出仓库不能为空", trigger: "change" }
        ],
        inboundWarehouseId: [
          { required: true, message: "调入仓库不能为空", trigger: "change" }
        ],
        operator: [
          { required: true, message: "经办人不能为空", trigger: "blur" }
        ],
        sourceStatus: [
          { required: true, message: "出库状态不能为空", trigger: "change" }
        ],
        transferQuantity: [
          { required: true, message: "销售数量不能为空", trigger: "blur" }
        ],
        transferAmount: [
          { required: true, message: "销售金额不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList();
    this.odTransferDetailsList = [];
    // this.DllocationCode();
    // this.DclocationCode();
  },
  methods: {


    calculateSalesAmount(row) {
      console.log('ZOO122:', JSON.stringify(this.odTransferDetailsList[row.index-1], null, 2));
      // alert(this.odTransferDetailsList[row.index-1].outboundWarehouseId+":"+row.transferQuantity);
      if (this.odTransferDetailsList[row.index-1].outboundWarehouseId < row.transferQuantity) {
        this.$modal.msgError('销售数量不能大于可用库存');
        row.transferQuantity = this.odTransferDetailsList[row.index - 1].outboundWarehouseId;
      }
      console.log('kkkk:', JSON.stringify(this.kuchun[0], null, 2));
    },

    // 库位查询
    async DlonWarehouseChange() {
      // const inventoryId = this.$route.query.id;
      // if (inventoryId == null) {
      const warehouseId = this.form.inboundWarehouseId;
      // alert('仓库：' + warehouseId)
      // 尝试将 warehouseId 转换为数字
      const warehouseIdLong = Number(warehouseId);
      console.log('转换后的仓库ID:', warehouseIdLong);

      if (!isNaN(warehouseIdLong) && warehouseIdLong > 0) { // 检查转换结果是否有效
        try {
          // 调用封装的方法获取对应的库存信息
          const response = await selectAllBsWhLocation(warehouseIdLong);
          console.log('后端响应调出:', JSON.stringify(response, null, 2));
          this.dlwhLocation = response.data.map(item => ({
            value: item.locationCode,
            label: item.locationName
          }));
          // this.updateTableData(); // 更新表格数据
          // 在这里触发库存查询
          for (const item of this.odTransferDetailsList) {
            if (item.dllocationCode) {
              this.DlfetchwhLocationContact(item.dllocationCode, item.productCode, item);
            }
          }
        } catch (error) {
          console.error('获取库位信息失败:', error);
          // 在这里可以提示用户失败信息
        }
      } else {
        console.error('无效的仓库ID:' + warehouseId);
        this.dlwhLocation = []; // 如果没有选择仓库，则重置库位
      }
    },
    async DconWarehouseChange() {
      // const inventoryId = this.$route.query.id;
      // if (inventoryId == null) {
      const warehouseId = this.form.outboundWarehouseId;


      // 尝试将 warehouseId 转换为数字
      const warehouseIdLong = Number(warehouseId);
      console.log('转换后的仓库ID:', warehouseIdLong);

      if (!isNaN(warehouseIdLong) && warehouseIdLong > 0) { // 检查转换结果是否有效
        try {
          // 调用封装的方法获取对应的库存信息
          const response = await selectAllBsWhLocation(warehouseIdLong);
          console.log('后端响应调入:', JSON.stringify(response, null, 2));
          this.dcwhLocation = response.data.map(item => ({
            value: item.locationCode,
            label: item.locationName
          }));
          // this.updateTableData(); // 更新表格数据
          // 在这里触发库存查询
          for (const item of this.odTransferDetailsList) {
            if (item.dclocationCode) {
              this.DcfetchwhLocationContact(item.dclocationCode, item.productCode, item);
            }
          }
        } catch (error) {
          console.error('获取库位信息失败:', error);
          // 在这里可以提示用户失败信息
        }
      } else {
        console.error("无效的仓库ID:" + warehouseId);
        this.dcwhLocation = []; // 如果没有选择仓库，则重置库位
      }
    },

    DcfetchwhLocationContact(selectedLocation, productCode, currentRow) {
      // console.log("选中的库位:", selectedLocation);
      // console.log("货品编号:", productCode); // 访问当前行的货品编号

      const query = {
        location: selectedLocation,
        productCode: productCode
      };

      // 调用 API 查询库存
      selectWhInventoryByCode(query)
        .then(response => {
          console.log("库存:" + JSON.stringify(response.data, null, 2));

          // 假设 response.data 是一个数组，我们只关心第一个元素
          if (response.data.length > 0) {
            const inventoryData = response.data[0];
            this.kuchun = response.data;
           //alert("库存:"+ inventoryData.currentInventory);
            // 直接更新当前行的 currentStock
            this.$set(currentRow, 'outboundWarehouseId', inventoryData.currentInventory); // 更新当前行的 currentStock
            console.log("更新后的当前库存:", currentRow.outboundWarehouseId); // 打印更新后的库存
            // this.kuchun = currentRow.outboundWarehouseId;
            // alert("库存2："+currentRow.outboundWarehouseId)
          } else {
            console.log("没有找到库存数据");
            // 如果没有找到，可以考虑将 currentStock 设置为空或者提示用户
            this.$set(currentRow, 'currentStock', 0); // 更新当前行的 currentStock
          }
        })
        .catch(error => {
          console.error('查询库存失败:', error);
        });
    },
    DlfetchwhLocationContact(selectedLocation, productCode, warehouseCode, currentRow) {
      // console.log("选中的库位:", selectedLocation);
      // console.log("货品编号:", productCode); // 访问当前行的货品编号

      const query = {
        location: selectedLocation,
        productCode: productCode,
        warehouseCode: warehouseCode
      };

      // 调用 API 查询库存
      selectWhInventoryByCode(query)
        .then(response => {
          console.log("库存:" + JSON.stringify(response.data, null, 2));

          // 假设 response.data 是一个数组，我们只关心第一个元素
          if (response.data.length > 0) {
            const inventoryData = response.data[0];
            // 直接更新当前行的 currentStock
            this.$set(currentRow, 'inboundWarehouseId', inventoryData.currentInventory); // 更新当前行的 currentStock
            console.log("更新后的当前库存:", currentRow.inboundWarehouseId); // 打印更新后的库存
          } else {
            console.log("没有找到库存数据");
            // 如果没有找到，可以考虑将 currentStock 设置为空或者提示用户
            this.$set(currentRow, 'currentStock', 0); // 更新当前行的 currentStock
          }
        })
        .catch(error => {
          console.error('查询库存失败:', error);
        });
    },

    indexMethod(index) {
      return index + 1; // 从1开始计数
    },
    // 更新货品
    replaceGoodsList() {
      this.odTransferDetailsList.forEach(selectedGood => {
        const index = this.goodsListAll.findIndex(good => good.id === selectedGood.id);
        if (index !== -1) {
          this.goodsListAll.splice(index, 1);
        }
      });
    },
    goodsClick(row) {
      console.log("row",row)
      // 处理选择变化的逻辑
      this.goodsInfo = row;
    },
    // 取消按钮
    cancel() {
      this.odTransferDetailsList=[]
      this.open = false;
    },
    // 弹框
    handleAddOdTransferDetails() {
      this.queryGoods.warehouseId = this.form.outboundWarehouseId;
      // alert('仓库名称:' + this.queryGoods.warehouseName)
      // console.log("sdd:",this.queryGoods)
      console.log("ss",this.queryGoods.warehouseId)
      selectquery(this.queryGoods.warehouseId).then(res =>{
        this.goodsListAll = res;
        console.log("adc:",res);
      })

      this.Goodsopen = true;
    },

    /** 查询库存调拨列表 */
    getList() {
      this.loading = true;
      listTransfer(this.queryParams).then(response => {
        // console.log("萨达安安:"+JSON.stringify( response.rows, null, 2));
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryTransferId: null,
        status: null,
        transferNumber: null,
        transferType: null,
        requestDate: null,
        outboundWarehouseId: null,
        inboundWarehouseId: null,
        sourceStatus: null,
        destinationStatus: null,
        transferQuantity: null,
        transferAmount: null,
        operator: null,
        notes: null,
        creator: null,
        departmentId: null,
        createTime: null,
        reviewer: null,
        reviewTime: null,
        isDeleted: '0',
        allocationOfGoods: null
        // odTransferDetails: {
        //   warehouseId: null,
        //   warehouseName: null
        // }
      };
      this.whInventoryList = [];
      this.odWarehouseList = [];
      this.resetForm("form");
    },
    // 查询经办人
    selUserall() {
      this.jhOpen = true;
      this.userLoading = true;
      listUser(this.userQueryParams).then(response => {
        this.userList = response.rows;
        this.userTotal = response.total;
        this.userLoading = false;
      })
    },
    // 添加货品确认按钮
    getGoodsClickRows() {
      console.log("萨达安安:"+JSON.stringify(this.goodsInfo, null, 2));
      this.Goodsopen = false;
      console.log("aa:" + this.goodsInfo);
      for (let i = 0; i < this.goodsInfo.length; i++) {
          const row = this.goodsInfo[i];
          const identifier = `${row.productCode}-${row.productModel}`;
          let existingItem = this.odTransferDetailsList.find(item => item.productCode === row.productCode && item.specificationNumber === row.productModel);
          console.log("identifier",this.odTransferDetailsList.find(item => item.productCode === row.productCode && item.specificationNumber === row.productModel))
          if (existingItem) {
            existingItem.transferQuantity = Number(existingItem.transferQuantity) + 1;
          } else {
            this.odTransferDetailsList.push({
              index: this.odTransferDetailsList.length + 1,
              productName: row.productName,
              productCode: row.productCode,
              specificationNumber: row.productModel,
              unit: row.productUnit,
              productType: row.productTypeList[0].productTypeName,
              outboundWarehouseId: row.outboundWarehouseId,
              inboundWarehouseId: row.inboundWarehouseId,
              dlLocationCode: row.dlLocationCode,
              dcLocationCode: row.dcLocationCode,
              transferQuantity: 1,
              inboundPrice: row.inboundPrice,
              notes: ''
            });
          }
        }

        this.calculateTotals();
        console.log("this.odTransferDetailsList",this.odTransferDetailsList)
      /* this.replaceSelectGoodsList() */
    },
    // 移除货品
    handleDetach(row) {
      this.selectedGoods = this.selectedGoods.filter(good => good.id !== row.id);
    },
    // 取消货品
    getGoodsClickCount() {
      this.Goodsopen = false;
    },
    //   设置默认值
    // replaceSelectGoodsList() {
    //   this.selectedGoods.forEach(selectedGood => {

    //   });
    // },
     // 采购人员选择
      userClick(row) {
      this.form.operator = row.userName;
      this.jhOpen = false;
    },
    // 审核
    handleAudit(row) {
      this.auditOptionVisible = true;
      console.log(row);
      this.form=row;
    },
    // 审核按钮
    confirmAudit() {
      this.form.outboundWarehouseId = this.outboundWarehouseId;
      this.form.status = this.auditOption;
      if (this.form.status != null) {
        updateAllocate(this.form).then(response =>{
          console.log('aa:' + this.form);
          if (this.form.status === '4') {
            this.$modal.msgSuccess('审核成功');
          } else {
            this.$modal.msgSuccess('以驳回');
          }
          this.auditOptionVisible = false;
          this.getList();
        })
      } else if (this.form.status == null) {
        this.$modal.msgSuccess('请选择');
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm2');
      this.userQueryParams.pageNum = 1;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryTransferId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 获取仓库信息列表
      listWarehouse().then(res=>{
        this.WareList = res.rows;
        this.updateGoods();
      });
      this.reset();
      this.open = true;
      this.title = '添加库存调拨';
      /** 获取编号*/
    getCode(5).then(response => {
        console.log(response);
        this.form.transferNumber = response.sequence;
        this.form.number = response.number;
        this.form.codeId = response.codeId;
      });
    },
  // 获取仓库信息
    updateAdd() {
      // 获取仓库信息列表
      listWarehouse().then(res=>{
        this.WareList = res.rows;
        this.updateGoods();
      });
      this.reset();
      this.open = true;
      this.title = '修改库存调拨';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
    this.updateAdd();
    this.reset();
    const inventoryTransferId = row.inventoryTransferId || this.ids;

    getTransfer(inventoryTransferId).then(response => {
        console.log('response111', response);
        this.form = response.data; // 确保这是响应式的

        this.odTransferDetailsList = response.data.odTransferDetailsList;
        this.open = true;
        this.title = '修改库存调拨';

        // 确保不直接操作这些而不更新状态
        if (this.form.inboundWarehouseId) {
            this.DlonWarehouseChange();
        }
        if (this.form.outboundWarehouseId) {
            this.DconWarehouseChange();
        }
        // 添加日志以查看赋值情况
        console.log('调入仓库 ID:', this.form.inboundWarehouseId);
        console.log('调出仓库 ID:', this.form.outboundWarehouseId);
    });
},
    /** 提交按钮 */
    submitForm() {
      if (!this.isClick) {
        this.$message.warning('请勿重复提交');
        return;
      }
      this.isClick = false;
      this.$refs["form"].validate(valid => {
        if (valid) {
        // alert(this.transferQuantity1+"L"+this.wmsTotalamount);
          this.form.odTransferDetailsList = this.odTransferDetailsList;
          this.form.transferAmount=this.totalAmount;
          this.form.transferQuantity=this.totalProductQuantity;
          // this.form.dlLocationCode
          if (this.form.inventoryTransferId != null) {
            updateTransfer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.isClick=true;
            })
              .catch(error => {
                this.isClick=true;
                console.error('请求失败:', error)
              })
          } else {
            console.log('萨达安安2:' + JSON.stringify(this.form, null, 2));
            this.form.odTransferDetailsList = this.odTransferDetailsList
            console.log('萨达安安12:' + JSON.stringify(this.odTransferDetailsList, null, 2));
           // alert('调拨数量:' + this.form.transferQuantity);
           // alert('当前库存：' + this.odTransferDetailsList.outboundWarehouseId);
            if (this.form.inboundWarehouseId != this.form.outboundWarehouseId) {
              console.log('添加数据:', JSON.stringify(this.form, null, 2));
              addTransfer(this.form).then(response => {
                console.log('添加数据:', JSON.stringify(response, null, 2));
                this.$modal.msgSuccess('新增成功');
                this.open = false;
                this.getList();
                this.isClick=true;
              }).catch(error=>{
                this.isClick=true;
              });
            }
            // eslint-disable-next-line eqeqeq
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryTransferId = row.inventoryTransferId || this.ids;
      // alert(inventoryTransferId);
      this.$modal.confirm('是否确认删除库存调拨编号为"' + inventoryTransferId + '"的数据项？').then(function() {
        return delTransfer(inventoryTransferId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 调拨明细删除按钮操作 */
    handleDeleteOdTransferDetails() {
      if (this.checkedOdTransferDetails.length == 0) {
        this.$modal.msgError("请先选择要删除的调拨明细数据");
      } else {
        const odTransferDetailsList = this.odTransferDetailsList;
        const checkedOdTransferDetails = this.checkedOdTransferDetails;
        this.odTransferDetailsList = odTransferDetailsList.filter(function(item) {
          // eslint-disable-next-line eqeqeq
          return checkedOdTransferDetails.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleOdTransferDetailsSelectionChange(selection) {
      this.checkedOdTransferDetails = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('transfer/transfer/export', {
        ...this.queryParams
      }, `transfer_${new Date().getTime()}.xlsx`)
    },
    calculateTotals() {
        let productCategories = new Set();
        let totalQuantity = 0;
        let totalAmount = 0;

        this.odTransferDetailsList.forEach(item => {
          console.log("item",item)
          productCategories.add(`${item.productCode}-${item.productModel}`);
          totalQuantity += Number(item.transferQuantity || 0);
          totalAmount += (Number(item.transferQuantity || 0) * Number(item.inboundPrice || 0));
        });
        this.totalProductCategory = productCategories.size;
        this.totalProductQuantity = totalQuantity;
        this.totalAmount = totalAmount.toFixed(2);
      }
  },
  watch:{
    odTransferDetailsList: {
      deep: true,
      handler() {
        this.calculateTotals();
      },
    },
  }
};
</script>
